#include "audio.h"
#include <iostream>
#include <cmath>
#include <thread>
#include <chrono>
#include <cstring>

AudioPlayer::AudioPlayer() : stream(nullptr), isPlaying(false) {
}

AudioPlayer::~AudioPlayer() {
    stop();
    if (stream) {
        Pa_CloseStream(stream);
    }
    Pa_Terminate();
}

bool AudioPlayer::initialize() {
    PaError err = Pa_Initialize();
    if (err != paNoError) {
        std::cerr << "PortAudio initialization failed: " << Pa_GetErrorText(err) << std::endl;
        return false;
    }
    
    err = Pa_OpenDefaultStream(&stream, 0, 1, paFloat32, 44100, 256, nullptr, nullptr);
    if (err != paNoError) {
        std::cerr << "Failed to open audio stream: " << Pa_GetErrorText(err) << std::endl;
        Pa_Terminate();
        return false;
    }
    
    err = Pa_StartStream(stream);
    if (err != paNoError) {
        std::cerr << "Failed to start audio stream: " << Pa_GetErrorText(err) << std::endl;
        Pa_CloseStream(stream);
        Pa_Terminate();
        return false;
    }
    
    return true;
}

void AudioPlayer::playBeep() {
    std::string command = "paplay /usr/share/sounds/gnome/default/alerts/swing.ogg";
    system(command.c_str());
}

void AudioPlayer::playMorseCode(const std::string& morseCode, int frequency, int baseTimeMs) {
    if (!stream) return;
    
    const float sampleRate = 44100.0f;
    
    for (char c : morseCode) {
        if (c == '.') {
            // 点：1个baseTime
            unsigned long numFrames = static_cast<unsigned long>(sampleRate * baseTimeMs / 1000.0f);
            float* buffer = new float[numFrames];
            generateSineWave(buffer, numFrames, frequency);
            Pa_WriteStream(stream, buffer, numFrames);

            delete[] buffer;
            //生成一个baseTimeMs的buffer，无声并写入流
            numFrames = static_cast<unsigned long>(sampleRate * baseTimeMs / 1000.0f);
            buffer = new float[numFrames];
            memset(buffer, 0, numFrames * sizeof(float));
            Pa_WriteStream(stream, buffer, numFrames);
            delete[] buffer;
            
            // 点/划之间的间隔：1个baseTime
            // std::this_thread::sleep_for(std::chrono::milliseconds(baseTimeMs));
        }
        else if (c == '-') {
            // 划：3个baseTime
            unsigned long numFrames = static_cast<unsigned long>(sampleRate * 3 * baseTimeMs / 1000.0f);
            float* buffer = new float[numFrames];
            generateSineWave(buffer, numFrames, frequency);
            Pa_WriteStream(stream, buffer, numFrames);
            delete[] buffer;
             //生成一个baseTimeMs的buffer，无声并写入流
            numFrames = static_cast<unsigned long>(sampleRate * baseTimeMs / 1000.0f);
            buffer = new float[numFrames];
            memset(buffer, 0, numFrames * sizeof(float));
            Pa_WriteStream(stream, buffer, numFrames);
            delete[] buffer;
            // 点/划之间的间隔：1个baseTime
            // std::this_thread::sleep_for(std::chrono::milliseconds(baseTimeMs));
        }
        else if (c == ' ') {
            // 字符之间的间隔：2个baseTime（因为点/划后已经有1个baseTime）
            // std::this_thread::sleep_for(std::chrono::milliseconds(3 * baseTimeMs));
             //生成一个baseTimeMs的buffer，无声并写入流
            unsigned long numFrames = static_cast<unsigned long>(sampleRate * 3*baseTimeMs / 1000.0f);
            float* buffer = new float[numFrames];
            memset(buffer, 0, numFrames * sizeof(float));
            Pa_WriteStream(stream, buffer, numFrames);
            delete[] buffer;
        }
    }
}

void AudioPlayer::stop() {
    if (stream && isPlaying) {
        Pa_StopStream(stream);
        Pa_StartStream(stream);
        isPlaying = false;
    }
}

// 修改这部分代码，添加 [[maybe_unused]] 属性
int AudioPlayer::paCallback([[maybe_unused]] const void *inputBuffer, 
                           [[maybe_unused]] void *outputBuffer, 
                           [[maybe_unused]] unsigned long framesPerBuffer, 
                           [[maybe_unused]] const PaStreamCallbackTimeInfo* timeInfo, 
                           [[maybe_unused]] PaStreamCallbackFlags statusFlags, 
                           [[maybe_unused]] void *userData) {
    // 这个简单实现中暂不需要回调
    return paContinue;
}

void AudioPlayer::generateSineWave(float* buffer, unsigned long frames, float frequency, float amplitude) {
    const float sampleRate = 44100.0f;
    static float phase = 0.0f;
    
    for (unsigned long i = 0; i < frames; ++i) {
        //(32000 * sin(2 * PI * freq * t))
        // buffer[i] = amplitude * sinf(2.0f * M_PI * frequency * phase / sampleRate);
        buffer[i] = amplitude * sin(2.0f * M_PI * frequency * phase / sampleRate);
        phase += 1.0f;
        if (phase >= sampleRate) {
            phase -= sampleRate;
        }
    }
}